# author: tgl
from rest_framework import serializers
from apps.api.testcase.models import TestCaseModel
from apps.api.interface.models import InterfaceModel
from utils.common import date_format


class TestCaseModelSerializer(serializers.ModelSerializer):
    interface = serializers.StringRelatedField(label='所属接口名称', help_text='所属接口名称')
    interface_id = serializers.PrimaryKeyRelatedField(queryset=InterfaceModel.objects.all(), label='所属接口ID',
                                                      help_text='所属接口ID')

    class Meta:
        model = TestCaseModel
        exclude = ["is_delete", "update_time"]
        extra_kwargs = {
            "name": {
                "min_length": 2,
                "max_length": 50,
                "error_messages": {
                    "min_length": "测试用例名称长度为 2-50 个字符！",
                    "max_length": "测试用例名称长度为 2-50 个字符！"
                }
            },
            "create_time": {
                "read_only": True,
                "format": date_format()
            }
        }

    def create(self, validated_data):
        interface = validated_data.pop("interface_id")
        validated_data["interface_id"] = interface.id
        return super().create(validated_data)

    def update(self, instance, validated_data):
        interface = validated_data.pop("interface_id")
        validated_data["interface_id"] = interface.id
        return super().update(instance, validated_data)


class TestCaseNameModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = TestCaseModel
        fields = ["id", "name"]


class RunTestCaseModelSerializer(serializers.ModelSerializer):
    env_id = serializers.IntegerField(label="运行环境id", help_text="运行环境id", write_only=True)

    class Meta:
        model = TestCaseModel
        fields = ["env_id"]
